package com.ece.pfe_rover_pvt_ines_ece_application.view;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import com.ece.pfe_rover_pvt_ines_ece_application.PFE_ROVER_PVT_INES_ECE_Application;
import com.ece.pfe_rover_pvt_ines_ece_application.R;
import com.ece.pfe_rover_pvt_ines_ece_application.model.Measurements;
import com.parse.ParseAnonymousUtils;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.ui.ParseLoginBuilder;

import android.app.ActionBar.LayoutParams;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.HorizontalScrollView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class TableActivity2 extends Activity {
	public boolean DEBUG_MODE = PFE_ROVER_PVT_INES_ECE_Application.DEBUG;
	private static final int LOGIN_ACTIVITY_CODE = 100;				
	private static final int SIGNIFICANT_NB = 5;
	
	private TextView tv_avgV, tv_avgI, tv_avgP, tv_avgL, tv_avgTpan, tv_avgTair, tv_avgSwind;	
	
	private  Button stats;
	
	private TableLayout tableLayout;
	private RelativeLayout root;
	private RelativeLayout.LayoutParams params;
	private ScrollView sv;
	private HorizontalScrollView hsv; 
		
	private int cl, rl;
	private String[] row;
	String[] column = { "EntryId\n", "ID PV\n(1,2)", "I \n(A)", "V\n(V)", "PUISSANCE\n(W)", "LUMINOSITE\n(W/m2)",
			"T PV\n(°C)", "T EXT\n(°C)", "GPS\n", "VITESSE VENT\n(m/s)", "TIMESTAMP\n" };
	
	String[] selectedFields = {"EntryId","IdPan", "I", "V", "P", "Lum", "Tpan",
			"Tair", "GPS", "Swind", "Date"};
	
	private List<Measurements> result = null;
	private boolean pv1,pv2, paramDefault;
	private long startDate, endDate;
	private SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
	
	private double avgI =0, avgV=0, avgP=0, avgL=0, avgTpan=0,avgTair=0, avgSwind=0;
	private double maxI=0, maxV=0, maxP=0, maxL=0, maxTpan=0,maxTair=0, maxSwind=0;
	private double minI=0, minV=0, minP=0, minL=0, minTpan=0,minTair=0, minSwind=0;
	private int maxI_id=0, maxV_id=0, maxP_id=0, maxL_id=0, maxTpan_id=0, maxTair_id=0, maxSwind_id=0;
	private int minI_id=0, minV_id=0, minP_id=0, minL_id=0, minTpan_id=0, minTair_id=0, minSwind_id=0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		DEBUG_MODE = false;
		//Activity that links menu button to the table layout
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_table2);								
		
		//Menu & subtitle
		ActionBar actionBar = getActionBar();		
		actionBar.setSubtitle(R.string.subtitle_table1);
		
		//Rows and Colums of the table		
		LayoutInflater mInflater = LayoutInflater.from(this);
		View contentView = mInflater.inflate(R.layout.activity_table2, null);
		root = (RelativeLayout) contentView;				
		
		
		tv_avgI = (TextView) findViewById(R.id.tv_avgI);
		tv_avgV = (TextView) findViewById(R.id.tv_avgV);
		tv_avgP = (TextView) findViewById(R.id.tv_avgP);
		tv_avgL = (TextView) findViewById(R.id.tv_avgL);
		tv_avgTair = (TextView) findViewById(R.id.tv_avgTair);
		tv_avgTpan = (TextView) findViewById(R.id.tv_avgTpan);
		tv_avgSwind = (TextView) findViewById(R.id.tv_avgSwind);
				
		
		
		Date d = new Date();		
		
		Intent intent = getIntent();
				
		pv1 = intent.getBooleanExtra("PV1", false);
		pv2 = intent.getBooleanExtra("PV2", false);
		paramDefault = intent.getBooleanExtra("paramDefault", false);
		startDate = intent.getLongExtra("startDate", d.getTime());
		endDate = intent.getLongExtra("endDate", d.getTime());
		
		System.out.println("PV1"+ pv1);
		System.out.println("PV2"+ pv2);
		
		if (pv1 & !pv2) {	            	
			
			ParseQuery<Measurements> query1 = ParseQuery.getQuery(Measurements.class);
		    query1.fromLocalDatastore();
			query1.selectKeys(Arrays.asList(selectedFields));
			query1.whereEqualTo("IdPan", 1);
			query1.whereGreaterThan("Date", startDate);
			query1.whereLessThan("Date", endDate);
			query1.orderByDescending("EntryId"); 
			try {
					result = new ArrayList<Measurements>();
				 	result = query1.find();
				} catch (ParseException e) {
					if(DEBUG_MODE) System.out.println("Query has not found anything");
					e.printStackTrace();
				}
			
			
			
			
		}else if(pv2 & !pv1) { 
			
			ParseQuery<Measurements> query2 = ParseQuery.getQuery(Measurements.class);
		    query2.fromLocalDatastore();
			query2.selectKeys(Arrays.asList(selectedFields));
			query2.whereEqualTo("IdPan", 2);
			query2.whereGreaterThan("Date", startDate);
			query2.whereLessThan("Date", endDate);
			query2.orderByDescending("EntryId"); 
			try {
					result = new ArrayList<Measurements>();
					result = query2.find();					
				} catch (ParseException e) {
					if(DEBUG_MODE) System.out.println("Query has not found anything");
					e.printStackTrace();
				}
		}else if (!(pv1 & pv2) || (pv1 & pv2))
		{
			System.out.println("here date: " + startDate + " | "+ sdf.format(startDate));
			
			System.out.println("here end date: " + endDate  + " | "+ sdf.format(endDate));
			ParseQuery<Measurements> query = ParseQuery.getQuery(Measurements.class);
			query.fromLocalDatastore();
			query.selectKeys(Arrays.asList(selectedFields));
			query.whereGreaterThanOrEqualTo("Date", startDate);
			query.whereLessThan("Date", endDate);
			query.orderByDescending("EntryId");
					
			try {
				result = new ArrayList<Measurements>();
				result = query.find();
			} catch (ParseException e) {
				if(DEBUG_MODE) System.out.println("Query has not found anything");
				e.printStackTrace();
			}		
			
		}
	   	
		computeStats();				    
		
		int tableSize = result.size();
		String[] row = new String[tableSize];

		rl = row.length;
		cl = column.length;
		
		sv = new ScrollView(this);
		sv.setScrollbarFadingEnabled(false);
		sv.setHorizontalScrollBarEnabled(true);
		tableLayout = createTableLayout(row, column, rl, cl);
		params = new RelativeLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		params.leftMargin = 400;

		hsv = new HorizontalScrollView(this);				
		hsv.addView(tableLayout);
		sv.addView(hsv);
		root.addView(sv, params);
		setContentView(root);
		
		((TextView) findViewById(R.id.nbEntry)).append(" "+result.size());
		
		Toast toast =  new Toast(getBaseContext());
		if(result.size() == 0) { 
			toast = Toast.makeText(getBaseContext(), "Désolé, il n'y a aucune mesure correspondant"
					+ " à votre recherche ", Toast.LENGTH_LONG);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
		}
	}
	
	private void computeStats() {
		avgI = average("I");
		avgV = average("V");
		avgP = average("P");
		avgL = average("Lum");
		avgTpan = average("Tpan");
		avgTair = average("Tair");
		avgSwind = average("Swind");
		
		minI = min("I");
		minV = min("V");
		minP = min("P");
		minL = min("Lum");
		minTpan = min("Tpan");
		minTair = min("Tair");
		minSwind = min("Swind");
		
		maxI = max("I");
		maxV = max("V");
		maxP = max("P");
		maxL = max("Lum");
		maxTpan = max("Tpan");
		maxTair = max("Tair");
		maxSwind = max("Swind");
	}

	@Override
	protected void onStart(){
		super.onStart();
				
		ProgressDialog dialog = ProgressDialog.show(this, "", 
                "Loading. Please wait...", false);
		dialog.dismiss();
	}
	
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub		
		super.onResume();		
		
		((TextView)findViewById(R.id.tv_avgI)).setText(String.valueOf(avgI));
		((TextView)findViewById(R.id.tv_avgV)).setText(String.valueOf(avgV));
		((TextView)findViewById(R.id.tv_avgP)).setText(String.valueOf(avgP));
		((TextView)findViewById(R.id.tv_avgL)).setText(String.valueOf(avgL));
		((TextView)findViewById(R.id.tv_avgTpan)).setText(String.valueOf(avgTpan));
		((TextView)findViewById(R.id.tv_avgTair)).setText(String.valueOf(avgTair));
		((TextView)findViewById(R.id.tv_avgSwind)).setText(String.valueOf(avgSwind));
		
		if (String.valueOf(minI) != null && String.valueOf(minI).length() > SIGNIFICANT_NB)
			((TextView)findViewById(R.id.tv_minI)).setText(String.valueOf(minI).substring(0, SIGNIFICANT_NB) + " (id "+minI_id+")");
		else
			((TextView)findViewById(R.id.tv_minI)).setText(String.valueOf(minI) + " (id "+minI_id+")");
		
		if (String.valueOf(minV) != null && String.valueOf(minV).length() > SIGNIFICANT_NB)
			((TextView)findViewById(R.id.tv_minV)).setText(String.valueOf(minV).substring(0, SIGNIFICANT_NB)  + " (id "+minV_id+")");
		else
			((TextView)findViewById(R.id.tv_minV)).setText(String.valueOf(minV) + " (id "+minV_id+")");
		
		if (String.valueOf(minP) != null && String.valueOf(minP).length() > SIGNIFICANT_NB)
			((TextView)findViewById(R.id.tv_minP)).setText(String.valueOf(minP).substring(0, SIGNIFICANT_NB)  + " (id "+minP_id+")");
		else
			((TextView)findViewById(R.id.tv_minP)).setText(String.valueOf(minP)  + " (id "+minP_id+")");
		
		if (String.valueOf(minL) != null && String.valueOf(minL).length() > SIGNIFICANT_NB)
			((TextView)findViewById(R.id.tv_minL)).setText(String.valueOf(minL).substring(0, SIGNIFICANT_NB)  + " (id "+minL_id+")");
		else
			((TextView)findViewById(R.id.tv_minL)).setText(String.valueOf(minL)  + " (id "+minL_id+")");
		
		if (String.valueOf(minTpan) != null && String.valueOf(minTpan).length() > SIGNIFICANT_NB)
			((TextView)findViewById(R.id.tv_minTpan)).setText(String.valueOf(minTpan).substring(0, SIGNIFICANT_NB)  + " (id "+minTpan_id+")");
		else
			((TextView)findViewById(R.id.tv_minTpan)).setText(String.valueOf(minTpan)  + " (id "+minTpan_id+")");
		
		if (String.valueOf(minTair) != null && String.valueOf(minTair).length() > SIGNIFICANT_NB)
			((TextView)findViewById(R.id.tv_minTair)).setText(String.valueOf(minTair).substring(0, SIGNIFICANT_NB)  + " (id "+minTair_id+")");
		else
			((TextView)findViewById(R.id.tv_minTair)).setText(String.valueOf(minTair)  + " (id "+minTair_id+")");
		
		if (String.valueOf(minSwind) != null && String.valueOf(minSwind).length() > SIGNIFICANT_NB)
			((TextView)findViewById(R.id.tv_minSwind)).setText(String.valueOf(minSwind).substring(0, SIGNIFICANT_NB)  + " (id "+minSwind_id+")");
		else
			((TextView)findViewById(R.id.tv_minSwind)).setText(String.valueOf(minSwind)  + " (id "+minSwind_id+")");
		
		if (String.valueOf(maxI) != null && String.valueOf(maxI).length() > SIGNIFICANT_NB)
			((TextView)findViewById(R.id.tv_maxI)).setText(String.valueOf(maxI).substring(0, SIGNIFICANT_NB)  + " (id "+maxI_id+")");
		else
			((TextView)findViewById(R.id.tv_maxI)).setText(String.valueOf(maxI) + " (id "+maxI_id+")");
		
		if (String.valueOf(maxV) != null && String.valueOf(maxV).length() > SIGNIFICANT_NB)
			((TextView)findViewById(R.id.tv_maxV)).setText(String.valueOf(maxV).substring(0, SIGNIFICANT_NB)  + " (id "+maxV_id+")");
		else
			((TextView)findViewById(R.id.tv_maxV)).setText(String.valueOf(maxV)  + " (id "+maxV_id+")");
		
		if (String.valueOf(maxP) != null && String.valueOf(maxP).length() > SIGNIFICANT_NB)
			((TextView)findViewById(R.id.tv_maxP)).setText(String.valueOf(maxP).substring(0, SIGNIFICANT_NB)  + " (id "+maxP_id+")");
		else
			((TextView)findViewById(R.id.tv_maxP)).setText(String.valueOf(maxP)  + " (id "+maxP_id+")");
		
		if (String.valueOf(maxL) != null && String.valueOf(maxL).length() > SIGNIFICANT_NB)
			((TextView)findViewById(R.id.tv_maxL)).setText(String.valueOf(maxL).substring(0, SIGNIFICANT_NB)  + " (id "+maxL_id+")");
		else
			((TextView)findViewById(R.id.tv_maxL)).setText(String.valueOf(maxL)  + " (id "+maxL_id+")");
		
		if (String.valueOf(maxTpan) != null && String.valueOf(maxTpan).length() > SIGNIFICANT_NB)
			((TextView)findViewById(R.id.tv_maxTpan)).setText(String.valueOf(maxTpan).substring(0, SIGNIFICANT_NB)  + " (id "+maxTpan_id+")");
		else
			((TextView)findViewById(R.id.tv_maxTpan)).setText(String.valueOf(maxTpan)  + " (id "+maxTpan_id+")");
		
		if (String.valueOf(maxTair) != null && String.valueOf(maxTair).length() > SIGNIFICANT_NB)
			((TextView)findViewById(R.id.tv_maxTair)).setText(String.valueOf(maxTair).substring(0, SIGNIFICANT_NB)  + " (id "+maxTair_id+")");
		else
			((TextView)findViewById(R.id.tv_maxTair)).setText(String.valueOf(maxTair)  + " (id "+maxTair_id+")");
		
		if (String.valueOf(maxSwind) != null && String.valueOf(maxSwind).length() > SIGNIFICANT_NB)
			((TextView)findViewById(R.id.tv_maxSwind)).setText(String.valueOf(maxSwind).substring(0, SIGNIFICANT_NB)  + " (id "+maxSwind_id+")");
		else
			((TextView)findViewById(R.id.tv_maxSwind)).setText(String.valueOf(maxSwind)  + " (id "+maxSwind_id+")");
	}

	public void makeCellEmpty(TableLayout tableLayout, int rowIndex,
			int columnIndex) {
		// get row from table with rowIndex
		TableRow tableRow = (TableRow) tableLayout.getChildAt(rowIndex);

		// get cell from row with columnIndex
		TextView textView = (TextView) tableRow.getChildAt(columnIndex);

		// make it black
		textView.setBackgroundColor(Color.BLACK);
	}

	public void setHeaderTitle(TableLayout tableLayout, int rowIndex,
			int columnIndex) {

		// get row from table with rowIndex
		TableRow tableRow = (TableRow) tableLayout.getChildAt(rowIndex);

		// get cell from row with columnIndex
		TextView textView = (TextView) tableRow.getChildAt(columnIndex);

		textView.setText("Hello");
	}

	private TableLayout createTableLayout(String[] rv, String[] cv,
			int rowCount, int columnCount) {
		// 1) Create a tableLayout and its params
		TableLayout.LayoutParams tableLayoutParams = new TableLayout.LayoutParams();
		TableLayout tableLayout = new TableLayout(this);
		tableLayout.setBackgroundColor(Color.BLACK);
		tableLayoutParams.height = 500;

		// 2) create tableRow params
		TableRow.LayoutParams tableRowParams = new TableRow.LayoutParams();
		tableRowParams.setMargins(1, 1, 1, 1);
		tableRowParams.weight = 1;

		System.out.println("Row count " + rowCount);
		System.out.println("Col count " + columnCount);
		for (int i = -1; i < rowCount; i++) {
			// 3) create tableRow
			TableRow tableRow = new TableRow(this);
			tableRow.setBackgroundColor(Color.BLACK);				
			
			for (int j = 0; j < columnCount; j++) {
				// 4) create textView
				TextView textView = new TextView(this);
				// textView.setText(String.valueOf(j));
				textView.setBackgroundColor(Color.WHITE);
				textView.setGravity(Gravity.CENTER);
				textView.setPadding(2, 0 , 2, 0);
				
				if (i == -1) {
					if(DEBUG_MODE) Log.d("TAAG", "set Column Headers");
					textView.setText(cv[j]);		
					textView.setTextColor(Color.parseColor("maroon"));
					textView.setTypeface(null, Typeface.BOLD);

				} else {					
					textView.setText(toTabString(result.get(i))[j]);
					textView.setTextColor(Color.BLACK);
				}
				// 5) add textView to tableRow
				tableRow.addView(textView, tableRowParams);
				//System.out.println(("j "+j));	
			}//System.out.println(("i "+i));
			// 6) add tableRow to tableLayout
			tableLayout.addView(tableRow, tableLayoutParams);
		}

		return tableLayout;
	}
	
	private String[] toTabString(Measurements m) {
						
		GregorianCalendar date = new GregorianCalendar();
		date.setTimeInMillis(m.getDate());
		String[]tab = new String[cl];
		tab[0] = String.valueOf(m.getEntryId());		
		tab[1] = String.valueOf(m.getInputId());
		tab[2] = String.valueOf(m.getI());
		tab[3] = String.valueOf(m.getV());
		tab[4] = String.valueOf(m.getP());
		tab[5] = String.valueOf(m.getLum());
		tab[6] = String.valueOf(m.getTpan());
		tab[7] = String.valueOf(m.getTair());
		tab[8] = String.valueOf(m.getGPS());
		tab[9] = String.valueOf(m.getSwind());
		tab[10] = String.valueOf(sdf.format(date.getTime()));
		
		//for(int i =0; i<tab.length; i++) System.out.println(tab[i]);
		return tab;
		
	}
	// Code that defines the link between the different buttons 
	
	/**
	 * Find the average value of each measurement type
	 * @param field
	 * @return
	 */

	private double average(String field) {		
		 Double sum = 0d;
		 for(int i = 0; i < result.size(); i++) {
			 switch(field) {
			 case "I":
				 sum += result.get(i).getI();				 
				 break;
			 case "V":
				 sum += result.get(i).getV();
				 break;
			 case "P":
				 sum += result.get(i).getP();
				 break;
			 case "Lum":
				 sum += result.get(i).getLum();
				 break;
			 case "Tpan":
				 sum += result.get(i).getTpan();
				 break;
			 case "Tair":
				 sum += result.get(i).getTair();
				 break;
			 case "Swind":
				 sum += result.get(i).getSwind();
				 break;
			 } 			
		 }	 		 
		return ((result.size() > 0 ) ? (sum/result.size()) : 0);
	}
	
	/**
	 * Find the value maximum of each measurement type
	 * @param field
	 * @return
	 */
	private double max(String field) {
		 Double max = 0d;
		 
		 for(int i = 0; i < result.size(); i++) {
			 switch(field) {
			 case "I":
				 if (max < result.get(i).getI()) { 
					 max = result.get(i).getI();
					 maxI_id = result.get(i).getEntryId();
				 }
				 break;
			 case "V":
				 if(max < result.get(i).getV()) {
					 max = result.get(i).getV();
					 maxV_id = result.get(i).getEntryId();
				 }
				 break;
			 case "P":
				 if (max < result.get(i).getP()) {
					 max = result.get(i).getP();
					 maxP_id = result.get(i).getEntryId();
				 }
				 break;
			 case "Lum":
				 if(max < result.get(i).getLum()) {
					 max = result.get(i).getLum();
					 maxL_id = result.get(i).getEntryId();
				 }
				 break;
			 case "Tpan":
				 if(max < result.get(i).getTpan()) {
					 max = result.get(i).getTpan();
					 maxTpan_id = result.get(i).getEntryId();
				 }
				 break;
			 case "Tair":
				 if(max < result.get(i).getTair()) {
					 max = result.get(i).getTair();
					 maxTair_id = result.get(i).getEntryId();
				 }
				 break;
			 case "Swind":
				 if (max < result.get(i).getSwind()) {
					 max = result.get(i).getSwind();
					 maxSwind_id = result.get(i).getEntryId();
				 }
				 break;
			 }
		 }		 
		return max;
	}
	
	/**
	 * Find the value minimum of each measurement type
	 * @param field
	 * @return
	 */
	private double min(String field) {
		 Double min = 10000000000d;
		 
		 for(int i = 0; i < result.size(); i++) {
			 
			 switch(field) {
			 case "I":
				 if (min > result.get(i).getI()) {
					 min = result.get(i).getI();
					 minI_id = result.get(i).getEntryId();
				 }
				 break;
			 case "V":
				 if(min > result.get(i).getV()) {
					 min = result.get(i).getV();
					 minV_id = result.get(i).getEntryId();
				 }
				 break;
			 case "P":
				 if (min > result.get(i).getP()) {
					 min = result.get(i).getP();
					 minP_id = result.get(i).getEntryId();
				 }
				 break;
			 case "Lum":
				 if(min > result.get(i).getLum()) {
					 min = result.get(i).getLum();
					 minL_id = result.get(i).getEntryId();
				 }
				 break;
			 case "Tpan":
				 if(min > result.get(i).getTpan()) {
					 min = result.get(i).getTpan();
					 minTpan_id = result.get(i).getEntryId();
				 }
				 break;
			 case "Tair":
				 if(min > result.get(i).getTair()) {
					 min = result.get(i).getTair();
					 minTair_id = result.get(i).getEntryId();
				 }
				 break;
			 case "Swind":
				 if (min > result.get(i).getSwind()) {
					 min = result.get(i).getSwind();
					 minSwind_id = result.get(i).getEntryId();
				 }
				 break;
			 }
		 }
		return min;
	}
	/**
	 * OnCreateOptionsMenu (Android method related to Activity class)
	 * Inflate the menu
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {		
		// Inflate the menu
		//this adds items to the action bar if it is present.		
		getMenuInflater().inflate(R.menu.action_logout, menu);
		getMenuInflater().inflate(R.menu.activity_main_actions, menu);		
		getMenuInflater().inflate(R.menu.action_login, menu);								
		return true;
	}
	
	/**
	 * onOptionsItemSelected (Android method related to Activity class)
	 * Start the activity related to a selected field in the menu
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {		
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		switch(id) {
		
		case R.id.measurements_list:
			startActivity(new Intent(this.getBaseContext(),MeasureActivity.class));			
			return true;
			
		case R.id.measurements_graphs:
			startActivity(new Intent(this.getBaseContext(),GraphsActivity.class));			
			return true;
			
		case R.id.referentiel:
			startActivity(new Intent(this.getBaseContext(),ReferentielActivity.class));			
			return true;
			
		case R.id.action_logout:			
			// Log out the current user
			ParseUser.logOut();
			// Create a new anonymous user
			ParseAnonymousUtils.logIn(null);
						
			// Unpin all the current objects
			ParseObject
					.unpinAllInBackground(PFE_ROVER_PVT_INES_ECE_Application.MEASUREMENTS_GROUP_NAME);
			
			//End the activity & go back the the previous one
			finish();
			
			return super.onOptionsItemSelected(item);
			
		case R.id.action_login:
			invalidateOptionsMenu();
			ParseLoginBuilder builder = new ParseLoginBuilder(this);
			startActivityForResult(builder.build(), LOGIN_ACTIVITY_CODE);
			
			return super.onOptionsItemSelected(item);
		
		default:			
				return super.onOptionsItemSelected(item);
		}
	}
	
	/**
	 * onPrepareOptionsMenu
	 */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {		
		
		if(DEBUG_MODE) System.out.println("---- Entering onPrepareOptopnsMenu method...");
		
		boolean realUser;
		super.onPrepareOptionsMenu(menu);
		if(ParseUser.getCurrentUser() != null){
			realUser = !ParseAnonymousUtils.isLinked(ParseUser
				.getCurrentUser());
			menu.findItem(R.id.action_login).setVisible(!realUser);								
			//Only registered user can see these buttons
			menu.findItem(R.id.action_logout).setVisible(realUser);	
			menu.findItem(R.id.measurements_list).setVisible(realUser);
			menu.findItem(R.id.measurements_graphs).setVisible(realUser);
			menu.findItem(R.id.referentiel).setVisible(realUser);
		}	
		menu.findItem(R.id.measurements_table).setVisible(false);
		return true;
	}
}
